<template>
  <view class="address-edit">
    <view class="form-item">
      <text class="label">收货人姓名</text>
      <input class="input" v-model="form.taker_name_" placeholder="请输入收货人姓名" />
    </view>
    <view class="form-item">
      <text class="label">手机号码</text>
      <input class="input" v-model="form.taker_phone_" placeholder="请输入手机号码" />
    </view>
    <view class="form-item">
      <text class="label">固定电话</text>
      <input class="input" v-model="form.taker_tel_" placeholder="请输入固定电话" />
    </view>
    <view class="form-item">
      <text class="label">所在地区</text>
      <picker class="input" @change="onRegionPicker" mode="region">
        <view class="input" v-if="form.taker_region_">{{ form.taker_region_ }}</view>
        <view class="input" v-else>选择地区</view>
      </picker>
    </view>
    <view class="form-item">
      <text class="label">详细地址</text>
      <input class="input" v-model="form.taker_address_" placeholder="请输入详细地址" />
    </view>
    <view class="form-item">
      <text class="label">设为默认地址</text>
      <switch :checked="form.is_default_ == 1" @change="onSwitch" color="#FFCC33" style="transform:scale(0.7)" />
    </view>

    <button class="button" @tap="submit">保存并使用</button>
  </view>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import Apis from "@/services/modules/order"

const query = defineProps<{ detail?: string }>()

uni.setNavigationBarTitle({
  title: query.detail ? "修改地址" : "新增地址",
})

const form = ref({
  is_default_: 0,
  taker_address_: "",
  taker_name_: "",
  taker_phone_: "",
  taker_region_: "",
  taker_region_ids_: "",
  taker_tel_: "",
})

if (query.detail) {
  form.value = JSON.parse(query.detail)
}

const onRegionPicker: UniHelper.RegionPickerOnChange = (ev) => {
  form.value.taker_region_ = ev.detail.value.join(",")
  form.value.taker_region_ids_ = ev.detail.code!.join(",")
}

const onSwitch: UniHelper.SwitchOnChange = (ev) => {
  form.value.is_default_ = ev.detail.value ? 1 : 0
}

const submit = async () => {
  await Apis.saveAddressApi(form.value)

  uni.showToast({
    icon: "success",
    title: "新增成功"
  })

  const timer = setTimeout(() => {
    clearTimeout(timer)
    uni.navigateBack()
  }, 200)
}

</script>

<style lang="scss">
page {
  background-color: #f6f6f6;
}

.address-edit {
  padding: 12px;

  .form-item {
    background-color: #fff;
    padding: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    border-bottom: 1px solid #dddddd;

    .label {
      width: 96px;
    }

    .input {
      flex: 1;
    }
  }

  .button {
    margin-top: 18px;
    background-color: $uni-color-warning;
    color: #fff;
  }
}
</style>
